<template>
  <div>
    <div class="search-term">
      <el-form :inline="true" :model="searchInfo" class="demo-form-inline">                      
        <el-form-item label="选品名称">
          <el-input placeholder="选品名称" v-model="searchInfo.selectGoodsName" clearable></el-input>
        </el-form-item>
        <el-form-item label="二级类目">
          <el-select clearable placeholder="二级类目" v-model="searchInfo.categorySecond">
            <el-option :key="item" :label="item" :value="item" v-for="item in categorySearchInfo"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="等级">
          <el-select clearable placeholder="推荐等级" v-model="searchInfo.recommendLevel">
            <el-option :key="item" :label="item" :value="item" v-for="item in recommendLevelList"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选品人">
          <el-select clearable placeholder="选品人" v-model="searchInfo.selectOwner">
            <el-option :key="item.label" :label="`${item.label}(${item.value})`" :value="item.label" v-for="item in userOptions"></el-option>
          </el-select>
        </el-form-item>
        
        
        <el-form-item>
          <el-button @click="onSubmit" type="primary" icon="el-icon-search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="openDialog" type="primary" icon="el-icon-plus">新增选品</el-button>
        </el-form-item>
        <el-form-item>
          <el-popover placement="top" v-model="deleteVisible" width="160">
            <p>确定要删除吗？</p>
              <div style="text-align: right; margin: 0">
                <el-button @click="deleteVisible = false" size="mini" type="text">取消</el-button>
                <el-button @click="onDelete" size="mini" type="primary">确定</el-button>
              </div>
            <el-button icon="el-icon-delete" slot="reference" type="danger">批量删除</el-button>
          </el-popover>
        </el-form-item>
        <el-form-item>
          <el-button @click="hidePicture" type="primary" icon="el-icon-refresh">{{hide_pic_content}}</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table
      :data="tableData"
      @selection-change="handleSelectionChange"
      border
      ref="multipleTable"
      stripe
      style="width: 100%"
      tooltip-effect="dark"
      :default-sort = "{prop: 'selectGoodsId', order: 'descending'}"
    >
    <el-table-column type="selection" width="40"></el-table-column>
    <!-- <el-table-column label="日期" width="300">
         <template slot-scope="scope">{{scope.row.CreatedAt|formatDate}}</template>
    </el-table-column> -->
    
    <el-table-column label="选品ID" prop="selectGoodsId" width="80"></el-table-column> 
    <el-table-column label="选品名称" prop="selectGoodsName" width="200"></el-table-column> 
  
    <!-- <el-table-column label="一级类目" prop="categoryFirst" width="80"></el-table-column>  -->
    
    <el-table-column label="二级类目" prop="categorySecond" width="80"></el-table-column> 
    
    <el-table-column label="图片" prop="imageUrl" width="130">
      <template width="120" slot-scope="scope">
        <img style="width:120px;height:120px;border:none;" :src="scope.row.imageUrl" v-show="isShow">
      </template>
    </el-table-column> 
    
    <el-table-column label="供应商" prop="supplier" width="70">
      <template  slot-scope="scope">
        <el-button type="success" size="mini" @click="linkRow(scope.row.supplier)">跳转</el-button>
      </template>
    </el-table-column> 
    
    <el-table-column label="进价" prop="purchasePrice" width="55"></el-table-column> 
    
    <el-table-column label="卖点" prop="sellPoint" width="250"></el-table-column> 
    
    <el-table-column label="推荐等级" prop="sellPoint" width="130">
      <template slot-scope="scope">  
        <span v-for="o in Math.abs(scope.row.selectRecommendationLevel)" :key="o" class="text item" style="font-weight:bold;font-size:16px" 
        :style="'color:'+(scope.row.selectRecommendationLevel>0?'red':'green')+';'">
          <i class="el-icon-star-on" style="margin-left:5px"></i>  
        </span>
      </template>
    </el-table-column> 
    
      <!-- <el-table-column fixed="right" label="操作" width="250"> -->
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button class="table-button" @click="checkInfo(scope.row)" size="small" type="primary">查看</el-button>
          <el-button class="table-button" @click="updateSelectList(scope.row)" size="small" type="primary">编辑</el-button>
          <el-button class="table-button" @click="recommendGoods(scope.row)" size="small" type="warning">赞</el-button>
          <el-button class="table-button" @click="unRecommendGoods(scope.row)" size="small" type="warning">踩</el-button>
          <el-button type="danger" size="small" @click="openCreateGoodsOrder(scope.row)">生成进货单</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      :current-page="page"
      :page-size="pageSize"
      :page-sizes="[10, 30, 50, 100]"
      :style="{float:'right',padding:'20px'}"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
      layout="total, sizes, prev, pager, next, jumper"
    ></el-pagination>

    <el-dialog :before-close="closeDialog" :visible.sync="dialogFormVisibleCheckInfo" title="选品详情">
      <el-form :model="rowData" label-position="right" label-width="80px">

          <el-card class="box-card" style="font-weight:bold;" shadow="hover">
            <div slot="header" class="clearfix" >
              <i class="el-icon-edit"></i><span style="font-weight:bold;font-size:16px">基本信息</span>
            </div>
            <el-row>
                <el-col :span="15">
                  <el-form-item label="选品名称"><span>{{ rowData.selectGoodsName }}</span></el-form-item>
                </el-col>
                 <el-col :span="5">
                  <el-form-item label="选品人"><span>{{ rowData.selectOwner }}</span></el-form-item>
                </el-col>
            </el-row>

            <el-row>
              <el-col :span="11">
                <el-form-item label="一级类目"><span>{{ rowData.categoryFirst }}</span></el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="二级类目"><span>{{ rowData.categorySecond }}</span></el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="5">
                <el-form-item label="供货链接" ><el-button type="success" size="mini" @click="linkRow(rowData.supplier)">跳转</el-button></el-form-item>
              </el-col>
              <el-col :span="6">
                <!-- <el-form-item label="供货价"><span>{{ rowData.purchasePrice }}￥</span></el-form-item> -->
                <el-form-item label="供货价" style="font-weight:normal;"><span>{{ rowData.purchasePrice }}￥</span></el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="竞品链接"><el-button type="success" size="mini" @click="linkRow(rowData.competitiveProducts)">跳转</el-button></el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="竞品售价" style="font-weight:normal;">
                  <span>{{ rowData.competitiveSellPrice }}JPY</span>
                  <span> = {{ rowData.competitiveSellPrice|convertJPY2RMB}} ￥</span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="推荐人等"><span>{{ rowData.selectReferrer }}</span></el-form-item>
            <!-- <el-form-item label="推荐等级">
              <span v-for="o in rowData.selectRecommendationLevel" :key="o" class="text item" style="font-weight:bold;font-size:16px" >
                <i class="el-icon-star-on" style="margin-left:5px"></i>  
              </span>
              <span v-for="o in Math.abs(rowData.selectRecommendationLevel)" :key="o" class="text item" style="font-weight:bold;font-size:16px" 
              :style="'color:'+(rowData.selectRecommendationLevel>0?'red':'green')+';'">
                <i class="el-icon-star-on" style="margin-left:5px"></i>  
              </span>
            </el-form-item> -->
            <el-form-item label="选品卖点"><span>{{ rowData.sellPoint }}</span></el-form-item>
        </el-card>
          <!-- 图片 -->
          <el-card class="box-card" style="margin-top: 10px;margin-bottom: 20px" shadow="hover">
            <div slot="header" class="clearfix" >
              <i class="el-icon-edit"></i><span style="font-weight:bold;font-size:16px">商品图片</span>
            </div>
            <template width="120">
              <img style="width:500px;height:500px;border:none;" :src="rowData.imageUrl">
            </template>
            <!-- <el-col :span="8">
              <template width="120">
                  <img style="width:200px;height:200px;border:none;" src="https://cbu01.alicdn.com/img/ibank/2019/720/859/12285958027_1374988884.jpg">
              </template>
            </el-col>
            <el-col :span="8">
              <template width="120">
                  <img style="width:200px;height:200px;border:none;" src="https://cbu01.alicdn.com/img/ibank/2019/720/859/12285958027_1374988884.jpg">
              </template>
            </el-col>
            <el-col :span="8">
              <template width="120">
                  <img style="width:200px;height:200px;border:none;" src="https://cbu01.alicdn.com/img/ibank/2019/720/859/12285958027_1374988884.jpg">
              </template>
            </el-col> -->
        </el-card>

          <!-- <el-form-item label="留言">
                <el-input type="textarea" :rows="5" placeholder="请输入内容" v-model="formData.sellPoint"></el-input>
          </el-form-item>           -->

          <el-form-item>
            <el-button @click="closeDialog" size="medium">关闭</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog :before-close="closeDialog" :visible.sync="dialogFormVisible" title="新增选品">
      <el-form :model="formData" label-position="right" label-width="80px">
      
          <el-form-item label="选品名称">
            <el-col :span="19"><el-input v-model.number="formData.selectGoodsName" clearable placeholder="请输入" size="medium" ></el-input></el-col>
          </el-form-item>

          <el-row>
            <el-col :span="8">
              <el-form-item label="一级类目" prop="categoryFirst">
                <el-select v-model="formData.categoryFirst" placeholder="请选择" size="medium" @change="handleChange">
                  <el-option :key="item" :label="item" :value="item" v-for="item in categoryFirstInit"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8" style="margin-left: 50px;">
              <el-form-item label="二级类目" prop="categorySecond">
                <el-select v-model="formData.categorySecond" placeholder="请选择" size="medium">
                  <el-option :key="item" :label="item" :value="item" v-for="item in categorySecondInit"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="商品图片">
              <el-input v-model="formData.imageUrl" clearable placeholder="请输入图片链接"></el-input>
          </el-form-item>
          
          <el-form-item label="供应商">
              <el-input v-model="formData.supplier" clearable placeholder="请输入产品链接" ></el-input>
          </el-form-item>
          
            <el-form-item label="进价">
                  <el-input-number v-model="formData.purchasePrice" :precision="2" clearable></el-input-number>
          </el-form-item>
          
          <el-form-item label="卖点">
                <el-input type="textarea" :rows="5" placeholder="请输入内容" v-model="formData.sellPoint"></el-input>
          </el-form-item>
          
            <el-form-item label="竞品链接">
                <el-input v-model="formData.competitiveProducts" clearable placeholder="请输入" ></el-input>
          </el-form-item>
          
            <el-form-item label="竞品售价">
                  <el-input-number v-model="formData.competitiveSellPrice" :precision="2" clearable></el-input-number>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="enterDialog">立即创建</el-button>
            <el-button @click="closeDialog">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 新增进货单 -->
    <el-dialog :before-close="closeDialog" :visible.sync="dialogFormVisibleGoodsOrder" title="新增进货单">
      <el-form :model="goodsOrderFormData" label-position="right" label-width="80px">
         <el-form-item label="商品名称:">
            <el-input v-model="goodsOrderFormData.goodsName" clearable placeholder="请输入" ></el-input>
      </el-form-item>
       
      <el-row>
        <el-col :span="8">
          <el-form-item label="一级类目" prop="categoryFirst">
            <el-select v-model="goodsOrderFormData.categoryFirst" placeholder="请选择" size="medium" @change="handleChange">
              <el-option :key="item" :label="item" :value="item" v-for="item in categoryFirstInit"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8" style="margin-left: 50px;">
          <el-form-item label="二级类目" prop="categorySecond">
            <el-select v-model="goodsOrderFormData.categorySecond" placeholder="请选择" size="medium">
              <el-option :key="item" :label="item" :value="item" v-for="item in categorySecondInit"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
       
      <el-form-item label="图片">
            <el-input v-model="goodsOrderFormData.imageUrl" clearable placeholder="请输入" ></el-input>
      </el-form-item>
       
         <el-form-item label="供应商">
            <el-input v-model="goodsOrderFormData.supplier" clearable placeholder="请输入" ></el-input>
      </el-form-item>
       
         <el-form-item label="进价">
              <el-input-number v-model="goodsOrderFormData.purchasePrice" :precision="2" clearable></el-input-number>
       </el-form-item>
       
         <el-form-item label="预售价">
              <el-input-number v-model="goodsOrderFormData.preSalePrice" :precision="2" clearable></el-input-number>
       </el-form-item>
       
         <el-form-item label="进货量"><el-input v-model.number="goodsOrderFormData.goodsCount" clearable placeholder="请输入"></el-input>
      </el-form-item>
       
      <el-form-item label="关联选品">
        <el-select v-model="goodsOrderFormData.goodsRelateSelectId" placeholder="请选择" size="medium">
          <el-option :key="item" :label="`${item.label}(${item.id})`" :value="item.id" v-for="item in selectGoodsList"></el-option>
        </el-select>
      </el-form-item>

        <el-form-item>
            <el-button type="primary" @click="createGoodsOrder">立即创建</el-button>
            <el-button @click="closeDialog">取消</el-button>
        </el-form-item>
       </el-form>
      <div class="dialog-footer" slot="footer">
      </div>
    </el-dialog>
    
  </div>

  
</template>

<script>
import {
    createSelectList,
    deleteSelectList,
    deleteSelectListByIds,
    updateSelectList,
    findSelectList,
    getSelectListList,
    recommend,
    unRecommend,
} from "@/api/selectList";  //  此处请自行替换地址
import { formatTimeToStr } from "@/utils/date";
import infoList from "@/mixins/infoList";
import {getUserList} from "@/api/user";
import {getSelectResearchList} from "@/api/selectResearch";
import {
    createGoodsOrder,
    deleteGoodsOrder,
    deleteGoodsOrderByIds,
    updateGoodsOrder,
    findGoodsOrder,
    getGoodsOrderList,
    getGoodsOrderById,
    createRelateBill
} from "@/api/goodsOrder";  //  此处请自行替换地址
export default {
  name: "SelectList",
  mixins: [infoList],
  data() {
    return {
      listApi: getSelectListList,
      dialogFormVisible: false,
      dialogFormVisibleCheckInfo: false,
      dialogFormVisibleGoodsOrder: false,
      type: "",
      deleteVisible: false,
      multipleSelection: [],
      formData: {
            selectGoodsId:0,
            categoryFirst:"",
            categorySecond:"",
            imageUrl:"",
            supplier:"",
            purchasePrice:0,
            preSalePrice:0,
            sellPoint:"",
            competitiveProducts:"",
            competitiveSellPrice:0,
            selectOwner:"",
            
      },
      userOptions:[],
      categoryFirstInit: [],
      categorySecondInit: [],
      categorySearchInfo: [],
      categoryMap: new Map(),
      recommendLevelList: ["1星", "2星", "3星", "4星", "5星"],
      value: 3.7,
      rowData:"",
      goodsOrderFormData: {
          selectGoodsId:0,
          goodsName:"",
          categoryFirst:"",
          categorySecond:"",
          imageUrl:"",
          supplier:"",
          purchasePrice:0,
          preSalePrice:0,
          goodsCount:0,
          logistics:"",
          goodsOrderOwner:"",
          goodsRelateSelectId:0,
          
      },
      isShow: false,
      hide_pic_content: '显示图片'
    };
  },
  filters: {
    formatDate: function(time) {
      if (time != null && time != "") {
        var date = new Date(time);
        // return formatTimeToStr(date, "yyyy-MM-dd hh:mm:ss");
        return formatTimeToStr(date, "yyyy-MM-dd");
      } else {
        return "";
      }
    },
    formatBoolean: function(bool) {
      if (bool != null) {
        return bool ? "是" :"否";
      } else {
        return "";
      }
    },
    // 日元换算人民币
    convertJPY2RMB: function(jpy){
      const exchangeRate = 6
      return (Number(jpy) * exchangeRate) / 100
    },
    convertRMB2JPY: function(rmb){
      const exchangeRate = 6
      return (Number(rmb) / exchangeRate) * 100
    },
  },
  methods: {
      //条件搜索前端看此方法
      onSubmit() {
        this.page = 1
        this.pageSize = 10               
        this.getTableData()
      },
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      deleteRow(row){
        this.$confirm('确定要删除吗?', '提示', {
          confirmButtonText: '非常确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
           this.deleteSelectList(row);
        });
      },
      async onDelete() {
        const ids = []
        if(this.multipleSelection.length == 0){
          this.$message({
            type: 'warning',
            message: '请选择要删除的数据'
          })
          return
        }
        this.multipleSelection &&
          this.multipleSelection.map(item => {
            ids.push(item.ID)
          })
        const res = await deleteSelectListByIds({ ids })
        if (res.code == 0) {
          this.$message({
            type: 'success',
            message: '删除成功'
          })
          if (this.tableData.length == ids.length) {
              this.page--;
          }
          this.deleteVisible = false
          this.getTableData()
        }
      },
    async updateSelectList(row) {
      const res = await findSelectList({ ID: row.ID });
      this.type = "update";
      if (res.code == 0) {
        this.formData = res.data.reselectList;
        this.dialogFormVisible = true;
      }
    },
    closeDialog() {
      this.dialogFormVisible = false;
      this.formData = {
          selectGoodsId:0,
          categoryFirst:"",
          categorySecond:"",
          imageUrl:"",
          supplier:"",
          purchasePrice:0,
          preSalePrice:0,
          sellPoint:"",
          competitiveProducts:"",
          competitiveSellPrice:0,
          selectOwner:"",
          
      };
      this.dialogFormVisibleCheckInfo = false;
      this.rowData = "";
      this.dialogFormVisibleGoodsOrder = false
    },
    async deleteSelectList(row) {
      const res = await deleteSelectList({ ID: row.ID });
      if (res.code == 0) {
        this.$message({
          type: "success",
          message: "删除成功"
        });
        if (this.tableData.length == 1) {
            this.page--;
        }
        this.getTableData();
      }
    },
    async enterDialog() {
      if(this.formData.selectGoodsName == "" || this.formData.categoryFirst == ""){
        this.$message({
          type:"info",
          message: "商品名称或商品类别不能为空"
        })
      }else{
        let res;
        switch (this.type) {
          case "create":
            res = await createSelectList(this.formData);
            break;
          case "update":
            res = await updateSelectList(this.formData);
            break;
          default:
            res = await createSelectList(this.formData);
            break;
        }
        if (res.code == 0) {
          this.$message({
            type:"success",
            message:"创建/更改成功"
          })
          this.closeDialog();
          this.getTableData();
        }
      }
    },
    openDialog() {
      this.type = "create";
      this.dialogFormVisible = true;
    },
    async initUserList(){
      const res =  await getUserList({ page:1, pageSize:9999});
      if(res.code == 0){
        res.data.list.forEach(element => {
          this.userOptions.push({
            "label": element.nickName,
            "value": element.userName
          })
        });
      }
    },
    async recommendGoods(row){
      let res;
      res = await recommend(row);
      if (res.code == 0) {
        this.$message({
            type: 'success',
            message: "赞成功"
        });
        this.getTableData();
      }
    },
    async unRecommendGoods(row){
      let res;
      res = await unRecommend(row);
      if (res.code == 0) {
        this.$message({
            type: 'success',
            message: "踩成功"
        });
        this.getTableData();
      }
    },
    async initCategoryList(){
      const res =  await getSelectResearchList({ page:1, pageSize:9999});
      if(res.code == 0){
        res.data.list.forEach(element => {
          this.categorySearchInfo.push(element.categorySecond);
          if(this.categoryMap.has(element.categoryFirst)){
            const tmp2 = this.categoryMap.get(element.categoryFirst)
            tmp2.push(element.categorySecond)
            this.categoryMap.set(element.categoryFirst, tmp2)
          }else{
            const tmp1 = [element.categorySecond]
            this.categoryMap.set(element.categoryFirst, tmp1)
          }

          // 初始化一级类目
          this.categoryFirstInit = [...this.categoryMap.keys()]
        });
      }
    },
    async handleChange(){
      this.formData.categorySecond = ""    // 清空二级级联选项
      if(this.formData.categoryFirst != ""){
        this.categorySecondInit = this.categoryMap.get(this.formData.categoryFirst)
      }
    },
    async linkRow(url){
      window.open(url);
    },
    async checkInfo(row){
      this.dialogFormVisibleCheckInfo = true
      this.rowData = row
    },
    async openCreateGoodsOrder(row){
      this.dialogFormVisibleGoodsOrder = true
      this.goodsOrderFormData = {
          goodsName: row.selectGoodsName,
          categoryFirst: row.categoryFirst,
          categorySecond: row.categorySecond,
          imageUrl: row.imageUrl,
          supplier: row.supplier,
          purchasePrice: row.purchasePrice,
          preSalePrice: row.preSalePrice,
          goodsCount:0,
          logistics:"",
          goodsRelateSelectId: row.selectGoodsId,
      };
    },
    async createGoodsOrder() {
      let res;
      res = await createGoodsOrder(this.goodsOrderFormData);
      if (res.code == 0) {
        this.$message({
          type:"success",
          message:"创建/更改成功"
        })
        this.closeDialog();
        this.getTableData();
      }
    },
    createBill(){
      this.$confirm('是否继续生成财务单?', '谨慎操作', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
           this.createBillYes();
      });
    },
    async createBillYes(){
      const billFormData = {
            billUseFor: "进货",
            billRelateGoodsOrder: this.formData.selectGoodsId,
            OrderAmount: this.formData.purchasePrice * this.formData.goodsCount,
            BillRemarks:"进货单号【" + this.formData.selectGoodsId +"】",
            goodsOrderId: this.formData.selectGoodsId,
            deliveryAmount: 10.0
      }
      const res = await createRelateBill(billFormData);
      if(res.code == 0){
        this.$message({
          type:"success",
          message:"创建财务单成功"
        })
      }
    },
    async checkLogistics(row){
      if(row.logistics == ""){
        this.$message({
          type: "error",
          message: "还未录入物流单号，无法查询"
        })
      }else{
        this.$message({
          type: "error",
          message: "还未录入物流单号，无法查询"
        })
      }
    },
    async hidePicture(){
      if(this.isShow == false){
        this.isShow = true
        this.hide_pic_content = '隐藏图片'
      }else{
        this.isShow = false
        this.hide_pic_content = '显示图片'
        
      }
    }
     
  },
  created() {
    this.initCategoryList()
    this.initUserList();
    this.getTableData();
  
}
};
</script>

<style scoped lang="scss">
  .button-box {
    padding: 10px 20px;
    .el-button {
      float: right;
    }
  }
  .el-tag--mini {
    margin-left: 5px;
  }
  .warning {
    color: #dc143c;
  }
</style>
<style>
  .el-select .el-input {
    width: 170px;
  }
  .input-with-select .el-input-group__prepend {
    background-color: #fff;
  }
  .transfer-footer {
    margin-left: 20px;
    padding: 6px 5px;
  }
  .admin-box .el-input__inner {
    height: 35px;
    line-height: 30px;
  }
  .el-card__body {
    padding-top: 0px;
    padding-bottom: 0px;
  }
</style>